package com.codejie.pms.controller;

import com.codejie.pms.entity.Customer;
import com.codejie.pms.entity.User;
import com.codejie.pms.service.CustomerService;
import com.codejie.pms.util.DateUtil;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;

@Controller
//@RestController
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    //去到显示客户信息界面
    @GetMapping("/customer_msg/{customerId}")
    public String getMsgPage(@PathVariable("customerId")String customerId,Model model){
        //this.customerId=id;
        Customer customer = customerService.getCustomer(customerId);
        model.addAttribute("customer",customer);
        //return "admin/updateCustomer";
        return "admin/customer_msg";
        //return "admin/reviseCustomer";
    }

    //打开所有客户信息页面
    //model用于给前端返回数据
    @RequestMapping("/emps")
    public String list(Model model) {
        Collection<Customer> customers = customerService.selectCustomerList();
        model.addAttribute("emps", customers);
        return "admin/all_customer";
    }

    //去到增加客户页面
    @GetMapping("/addCustomer")
    public String toAddCustomer(Model model){
        return "admin/addCustomer";
    }

    //增加客户
    @PostMapping("/addCustomer")
    public String addCustomer(Customer customer){
        if(customer.getCustomerId()!=null)
            customerService.addCustomer(customer);
        return "redirect:/emps";    //返回emps请求 到展示所有客户信息页面
    }

    //去到修改客户信息页面
    @GetMapping("/reviseCustomer/{customerId}")
    public String getUpdatePage(@PathVariable("customerId")String customerId,Model model){
        Customer customer = customerService.getCustomer(customerId);
        model.addAttribute("customer",customer);
        return "admin/reviseCustomer";
        //return "admin/customer_msg";
    }

    //修改客户
    @PostMapping("/reviseCustomer")
    public String reviseMethod(Customer customer){
        customerService.updateCustomer(customer);
        return "redirect:/emps";
    }

    @GetMapping("/deleteCustomer/{customerId}")
    public String deleteMethod(@PathVariable("customerId")String customerId,Model model){
        customerService.deleteCustomer(customerId);
        return "redirect:/emps";
    }

    //String theSearchCustomerId; //保存搜索的客户id
    //获取搜索的post请求
    @PostMapping("/searchCustomer")
    public String searchCustomer(String customerId,Model model){
        Customer customer = customerService.getCustomer(customerId);
        model.addAttribute("emps",customer);
        return "admin/all_customer";
//        this.theSearchCustomerId=customerId;
//        return "redirect:/getSearchCustomer";   //返回到getSearchCustomer请求
    }

    //返回展示所有客户页面，但是只有搜索的客户值
//    @RequestMapping("/getSearchCustomer")
//    public String getSearchCustomer(Model model){
//        Customer customer = customerService.getCustomer(theSearchCustomerId);
//        model.addAttribute("emps",customer);
//        return "admin/all_customer";
//    }


    //以execl导出客户列表
    @RequestMapping(value = "/customer/export")
    public void exportallDocumentaryExcel(HttpServletResponse response) throws IOException {
        try {
            List<Customer> customerList = customerService.selectCustomerList();
            // 在内存中创建一个Excel文件，通过输出流写到客户端提供下载
            // 内存中保留 10000 条数据，以免内存溢出，其余写入 硬盘
            SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(XSSFCellStyle.ALIGN_CENTER);//SXSSFWorkbook方式的居中
            // 创建一个sheet页
            SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet("表格");
            // 分别设置Excel列的宽度

            for(int i=0;i<10;i++){
                sheet.setColumnWidth(i, 4000);
            }
            // 创建标题
            SXSSFRow headRow = (SXSSFRow) sheet.createRow(0);
            headRow.createCell(0).setCellValue("客户号");
            headRow.createCell(1).setCellValue("姓名");
            headRow.createCell(2).setCellValue("电话");
            headRow.createCell(3).setCellValue("邮箱");
            headRow.createCell(4).setCellValue("qq");
            headRow.createCell(5).setCellValue("性别");

            for (Customer customer : customerList) {
                // 创建行
                SXSSFRow dataRow = (SXSSFRow) sheet.createRow(sheet.getLastRowNum() + 1);

                dataRow.createCell(0).setCellValue(customer.getCustomerId());
                dataRow.createCell(1).setCellValue(customer.getCustomerName());
                dataRow.createCell(2).setCellValue(customer.getPhone());
                dataRow.createCell(3).setCellValue(customer.getEmail());
                dataRow.createCell(4).setCellValue(customer.getQq());
                dataRow.createCell(5).setCellValue(customer.getGender()==0?"女":"男");
            }

            // 设置Excel文件名，并以中文进行编码
            String codedFileName = new String("客户列表".getBytes("gbk"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + codedFileName + DateUtil.getCurrentTime2()
                    +".xlsx");
            // 响应类型,编码
            response.setContentType("application/octet-stream;charset=UTF-8");
            // 形成输出流
            OutputStream osOut = response.getOutputStream();
            // 将指定的字节写入此输出流
            workbook.write(osOut);
            // 刷新此输出流并强制将所有缓冲的输出字节被写出
            osOut.flush();
            // 关闭流
            osOut.close();
            /*
             * dispose of temporary files backing this workbook on disk
             * 处理在磁盘上备份此工作簿的临时文件 SXSSF分配临时文件，必须始终清除显式，通过调用dispose方法
             */
            workbook.dispose();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println( "导出客户失败！失败信息："+e.getMessage());
        }
    }
}
